package com.newsee.remote.idm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.common.bean.JsonResult;
import com.newsee.remote.common.bean.JsonReturn;
import com.newsee.remote.common.database.entity.SystemUsersThird;
import com.newsee.remote.common.database.mapper.SystemUsersThirdMapper;
import com.newsee.remote.common.dto.idm.SystemUserDTO;
import com.newsee.remote.common.enumeration.UserStatusChangeEnum;
import com.newsee.remote.common.exception.ServiceException;
import com.newsee.remote.common.utils.tools.XmlBuildUtil;
import com.newsee.remote.common.utils.webservice.HttpWebserviceExecutor;
import com.newsee.remote.idm.service.ISystemUsersThirdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

import static org.apache.catalina.manager.Constants.CHARSET;

/**
 * <p>
 * 用户服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-07-11
 */
@Slf4j
@Service
public class SystemUsersThirdServiceImpl extends ServiceImpl<SystemUsersThirdMapper, SystemUsersThird> implements ISystemUsersThirdService {

    /**
     * 事务ID前缀—用户
     */
    private final static String BIZTRANSACTIONID_PRE_USER = "WY_WZXTUser_300_";

    /**
     * 融创标准请求
     */
    private final static String XMLNS_STR_USER = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http://www.ekingwin.com/esb/header/v1\" xmlns:pub=\"http://www.ekingwin.com/esb/PUBLIC_SUNAC_300_queryIdmUserData\">\n";

    /**
     * 循环调用idm信息查询接口，每页100，一天同步一次
     */
    private final static int TIMES = 100;

    @Value("${idmUserUrl}")
    private String idmUserUrl;

    @Value("${systemID}")
    private String systemID;

    @Value("${account}")
    private String account;

    @Value("${password}")
    private String password;

    @Value("${idmUserMethod}")
    private String idmUserMethod;

    @Override
    public JsonResult sunacUser(String startTime, String endTime) {
        for (int i = 1; i <= TIMES; i++) {
            //xml请求封装
            String params = XmlBuildUtil.makeXml(XMLNS_STR_USER, idmUserMethod, systemID, account, password, i, BIZTRANSACTIONID_PRE_USER, startTime, endTime);
            String response;
            try {
                response = HttpWebserviceExecutor.doHttpMethod(idmUserUrl, params);
                if (StringUtils.isNotEmpty(response)) {
                    //当页数据为空，停止
                    if ("<LIST></LIST>".equals(response)) {
                        break;
                    } else {
                        handleResponse(response);
                    }
                }
            } catch (Exception e) {
                //同步出错，停止同步
                break;
            }
        }
        return JsonReturn.succ();
    }

    /**
     * 解析返回结果
     *
     * @param list 返回
     */
    private void handleResponse(String list) throws ServiceException {
        try {
            SAXReader reader = new SAXReader();
            // 根据字符串构建字节数组输入流
            InputStream isList = new ByteArrayInputStream(list.getBytes(CHARSET));
            // 命令阅读器从输入流中读取文档对象
            Document documentList = reader.read(isList);
            // 获得文档对象的根节点
            List<Element> users = documentList.getRootElement().elements();
            for (Element user : users) {
                SystemUserDTO systemUserDTO = new SystemUserDTO();

                //手机号
                Element mobile = user.element("Mobile");
                if (null != mobile) {
                    systemUserDTO.setMobilePhone(mobile.getText());
                }

                //登录用户名
                Element userLogin = user.element("UserLogin");
                if (null != userLogin) {
                    systemUserDTO.setAccount(userLogin.getText());
                }

                Element username = user.element("Username");
                if (null != username) {
                    systemUserDTO.setUserName(username.getText());
                }

                //用的是融创部门编号，不是部门Id
                Element userOrganID = user.element("UserDeptNo");
                if (null != userOrganID) {
                    systemUserDTO.setDepartmentID(userOrganID.getText());
                }

                Element userStatus = user.element("UserStatus");
                if (null != userStatus) {
                    systemUserDTO.setUserStatus(UserStatusChangeEnum.getTextByCode(userStatus.getText()));
                }

                //主键
                Element userEmployeeID = user.element("UserEmployeeID");
                if (null != userEmployeeID) {
                    systemUserDTO.setUserEmployeeID(userEmployeeID.getText());
                }
                sync(systemUserDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("人员组织增量同步出错" + e.getMessage());
            throw new ServiceException();
        }
    }


    @Override
    public JsonResult sync(SystemUserDTO systemUserDTO) {
        String userEmployeeID = systemUserDTO.getUserEmployeeID();

        //判断是新增还是修改
        QueryWrapper<SystemUsersThird> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserID", userEmployeeID);
        SystemUsersThird systemUsers = getOne(queryWrapper);
        LocalDateTime now = LocalDateTime.now();
        //所在部门
        String departmentID = systemUserDTO.getDepartmentID();
        //新增
        if (null == systemUsers) {
            systemUsers = new SystemUsersThird();
            systemUsers.setUserID(userEmployeeID);
        }
        //修改
        else {
            systemUsers.setUpdateTime(now);
        }

        //用户名称
        String userName = systemUserDTO.getUserName();
        if (StringUtils.isNotBlank(userName)) {
            systemUsers.setUserName(userName);
        }
        if (StringUtils.isNotBlank(departmentID)) {
            systemUsers.setDepartmentID(departmentID);
        }
        //用户状态
        Integer userStatus = systemUserDTO.getUserStatus();
        if (null != userStatus) {
            systemUsers.setUserStatus(userStatus);
        }
        //手机号
        String mobilePhone = systemUserDTO.getMobilePhone();
        if (StringUtils.isNotBlank(mobilePhone)) {
            systemUsers.setMobilePhone(mobilePhone);
        }

        String account = systemUserDTO.getAccount();
        if (StringUtils.isNotEmpty(account)) {
            systemUsers.setAccount(account);
        }
        saveOrUpdate(systemUsers);
        return JsonReturn.succ();
    }
}
